﻿using System;
using System.Windows;
using GalaSoft.MvvmLight.Ioc;
using Gumini.JulaDB.Navigator.Logic;
using Gumini.JulaDB.Navigator.ViewModels;

namespace Gumini.JulaDB.Navigator
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            SimpleIoc.Default.Register<MainWindowViewModel>();
            SimpleIoc.Default.Register<ConnectionWindowViewModel>();
            SimpleIoc.Default.Register<ConnectionProvider>();
            SimpleIoc.Default.Register<ScriptProvider>();

            SimpleIoc.Default.GetInstance<MainWindowViewModel>();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            try
            {
                for (int i = 0; i < e.Args.Length; i++)
                {
                    var arg = e.Args[i];
                    switch (arg)
                    {
                        case "-memorydb":
                            SimpleIoc.Default.GetInstance<ConnectionProvider>().ConnectToInMemoryDatabase();
                            break;
                        case "-filedb":
                            if (++i < e.Args.Length)
                                SimpleIoc.Default.GetInstance<ConnectionProvider>().ConnectToFileDatabase(e.Args[i]);
                            else
                                throw new ArgumentException("Database file path is not specified");
                            break;
                        case "-script":
                            if (++i < e.Args.Length)
                                SimpleIoc.Default.GetInstance<ScriptProvider>().Open(e.Args[i]);
                            else
                                throw new ArgumentException("Script file path is not specified");
                            break;
                        default:
                            throw new ArgumentException(String.Format("Parameter {0} is not supported", arg));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error when trying parse the command line arguments: " + Environment.NewLine + ex.ToString(),
                    "Unable to launch", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }
        }
    }
}
